<template>
<div class="add-graph-right">

    <Collapse v-model="activeNames"  class="right-content">
        <Panel name="1">
            图表属性
            <div slot="content">
                <zl-graph :chart-options="chartOptions" @change-chart-options="changeChartOptions"></zl-graph>
            </div>
        </Panel>
        <Panel name="2">
            图表类型
            <ul class="right-graph-type" slot="content">
                <li class="disabled" v-for="(item,index) in graphAllList" :key="index"
                  :class="{'active':item.active,'selected':item.value==graphType}">
                    <div @click="choiseChartType(item)"  class="svg-full">
                    </div>
                    <embed :src="url+item.icon" width="30" height="30" type="image/svg+xml" :class="{'active':item.active,'selectedEmbed':item.value==graphType}" />
                    <div>{{item.name}}</div>
                </li>
            </ul>
        </Panel>
        <Panel name="basic">
          基础属性
          <div slot="content">
              <!-- 卡片 -->
              <zl-basic-card v-if="graphType === 'card'" v-bind="$props" @change-graph-options="changeGraphOptions"></zl-basic-card>
              <!-- 折线 -->
              <zl-color v-if="graphType !== 'card' && graphType !== 'img' && graphType !== 'text'"
                :graphOptions="graphOptions"
                :numbers="numbers"
                :groups="groups"
                :graphType="graphType"
                @changeGraphOptions="changeGraphOptions">
              </zl-color>
              <zl-align v-if="graphType === 'table'" :graphOptions="graphOptions" @changeGraphOptions="changeGraphOptions"></zl-align>
              <zl-basic-table v-if="graphType === 'table'" :graphOptions="graphOptions" @changeGraphOptions="changeGraphOptions"></zl-basic-table>
              <zl-size :graphOptions="graphOptions" @changeSeries="changeSeries" v-if="graphType === 'line' || graphType === 'line_area' "></zl-size>
              <zl-symbol :graphOptions="graphOptions" @changeSeries="changeSeries" v-if="graphType === 'line' || graphType === 'line_area' "></zl-symbol>
              <!-- 文本 -->
              <!-- <zl-text ref="ZlText" :graphOptions="graphOptions"  @changeText="changeText" v-if="graphType === 'text'"></zl-text> -->
              <!-- 图片 -->
              <zl-img v-if="graphType === 'img'" :echartImgURL="echartImgURL"></zl-img>
              <!-- 环形 -->
              <div v-if="graphType === 'pie_more'" class="m-t-20">
                <div class="right-row">
                    <span class="r-tit">内环大小</span>
                    <div class="r-cnt">
                        <Slider v-model="ring.innerRing" @on-change="changeRing" :min="0" :max="100" :tip-format="innerRingSlider"></Slider>
                    </div>
                </div>
                <div class="right-row">
                    <span class="r-tit">外环大小</span>
                    <div class="r-cnt">
                        <Slider v-model="ring.outerRing" @on-change="changeRing"  :min="0" :max="100" :tip-format="outerRingSlider"></Slider>
                    </div>
                </div>
              </div>
              <!-- 条形宽度 -->
              <zl-bar-width v-if="graphType === 'bar' || graphType === 'bar_type'" :graphOptions="graphOptions" @changeSeries="changeSeries"></zl-bar-width>
              <!-- 文本编辑器 -->
              <div v-if="graphType === 'text'" class="m-t-20">
                <div class="zl-attr-item-body" @click="showEditBox">
                  <span class="zl-attr-item__title">文本</span>
                </div>
                <zl-text-edit-box v-if="graphType === 'text'" ref="textEditBox" @changeText="changeText" :graphOptions="graphOptions"></zl-text-edit-box>
              </div>
          </div>
        </Panel>
        <Panel name="3" v-show="noTitle.indexOf(graphType) === -1">
          标题
          <div slot="content">
            <zl-title v-bind="$props" @change-graph-options="changeGraphOptions"></zl-title>
          </div>
        </Panel>
        <Panel name="legend" v-show="noLegend.indexOf(graphType) === -1">
          图例
          <div slot="content">
            <zl-legend v-bind="$props" @change-graph-options="changeGraphOptions"></zl-legend>
          </div>
        </Panel>
        <Panel  name="4" v-show="noXaxis.indexOf(graphType) === -1">
            坐标X轴
            <div slot="content" >
                <zl-xaxis v-bind="$props" @change-graph-options="changeGraphOptions"></zl-xaxis>
            </div>
        </Panel>
        <Panel name="6" v-show="noYaxis.indexOf(graphType) === -1">
            坐标Y轴
            <div slot="content">
              <zl-yaxis v-bind="$props" @change-graph-options="changeGraphOptions"></zl-yaxis>
            </div>
        </Panel>
        <Panel  name="5" v-show="noSeries.indexOf(graphType) === -1">
            图形属性
            <div slot="content"  >
                <options-series  :series="graphOptions.series" :graphOptions="graphOptions" :numbers="numbers"></options-series>
            </div>
        </Panel>
        <Panel  name="7" class="graph-panel" v-show="graphType !== 'img'">
            背景
            <div slot="content">
              <RadioGroup v-model="backdrop.control" vertical @on-change="backdropSelect">
                <div class="right-row">
                  <div class="r-tit">
                    <Radio :label="backdrop.color" class="m-b-10">
                        <span>颜色</span>
                    </Radio>
                  </div>
                  <div class="r-cnt">
                    <ColorPicker v-model="backdrop.colorPicker" @on-change="backdropSelect" alpha></ColorPicker>
                  </div>
                </div>
                <div class="right-row">
                  <div class="r-tit">
                    <Radio :label="backdrop.img">
                        <span>图片</span>
                    </Radio>
                  </div>
                  <div class="r-cnt">
                    <Upload action=""
                    :before-upload="handleBeforeUpload"
                    :show-upload-list="false">
                        <Button icon="ios-cloud-upload-outline">jpg/png/gif/bmp</Button>
                    </Upload>
                  </div>
                </div>
              </RadioGroup>
            </div>
        </Panel>
    </Collapse>
</div>
</template>

<script>
import util from  'util'
import getData from 'getData'
import optionsSeries from './options-series.vue'
import ZlGraph from '@/components/echart-config/zl-graph'
import ZlColor from '@/components/echart-config/zl-color'
import ZlSize from '@/components/echart-config/zl-size'
import ZlSymbol from '@/components/echart-config/zl-symbol'
import ZlTitle from '@/components/echart-config/zl-title'
import ZlLegend from '@/components/echart-config/zl-legend'
import ZlXaxis from '@/components/echart-config/zl-xaxis'
import ZlYaxis from '@/components/echart-config/zl-yaxis'
import ZlBasicCard from '@/components/echart-config/zl-basic-card'
import ZlImg from '@/components/echart-config/zl-img'
import ZlAlign from '@/components/echart-config/zl-align'
import ZlBasicTable from '@/components/echart-config/zl-basic-table'
import ZlText from '@/components/other/zl-text'
import ZlBarWidth from '@/components/echart-config/zl-bar-width'
import ZlTextEditBox from '@/components/other/zl-text-edit-box'
import {chartUtil,chartOptions} from '@/assets/js/graph-chart'
import config from '../../../api/service/config.js'
const fileUploadURL = ZLST_BIGDATA_CONFIG_DEV.UPLOAD_SERVER
const fileAccessURL = ZLST_BIGDATA_CONFIG_DEV.ACCESS_SERVER
export default {
    name: 'graphRight',
    components:{optionsSeries, ZlColor, ZlSize, ZlSymbol, ZlText, ZlTitle, ZlLegend, ZlXaxis, ZlYaxis, ZlGraph, ZlBasicCard, ZlImg, ZlTextEditBox, ZlAlign, ZlBasicTable, ZlBarWidth},
    props: {
        //初始化默认的options参数
        initoptions:{
            type:Object,
            default:function(){
                return {};
            }
        },
        //可以选择的图表的列表集合
        graphChartList:{
            type:Array,
            default:function () {
                return []
            }
        },
        initdata:{
            type:Object,
            default: function () {
                return {}
            }
        },
        //当前选择的图表类型
        graphType:{
            type:String
        },
        graphOptions:{
            type:Object,
            default:function(){
                return {};
            }
        },
        numbers:{
            type:Array
        },
        groups:{
            type:Array
        }
    },
    data () {
        return {
            url:'',
            activeNames:['1','2','3','4','5','6','7', 'basic', 'legend'],
            chartOptions:{
                graphName:'',
                graphType:'',
                access:'private',
                graphX:{},
                graphY:{},
                graph:{},
                remark:''
            },
            graphAllList:[
                {value:"card",name:"卡片",icon:"static/svg/card.svg", type: 'other'},
                {value:"text",name:"文本",icon:"static/svg/text.svg", type: 'other'},
                {value:"img",name:"图片",icon:"static/svg/img.svg", type: 'other'},
                {value:"table",name:"表格图",icon:"static/svg/table-map.svg", type: 'other'},
                {value:"line",name: "折线图",icon:"static/svg/line-chart.svg", type: 'chart'},
                {value:"line_area",name:"折线面积",icon:"static/svg/polyline-area.svg", type: 'chart'},
                {value:"gauge",name:"计量图",icon:"static/svg/metering-chart.svg", type: 'chart'},
                {value:"scatter",name:"散点图",icon:"static/svg/scatter-plot.svg", type: 'chart'},
                {value:"bar",name:"柱状图",icon:"static/svg/histogram.svg", type: 'chart'},
                {value:"bar_type",name:"条形图",icon:"static/svg/bar-chart.svg", type: 'chart'},
                {value:"funnel",name:"漏斗图",icon:"static/svg/funnel-chart.svg", type: 'chart'},
                {value:"pie",name:"饼图",icon:"static/svg/pie-chart.svg", type: 'chart'},
                {value:"map",name:"地图",icon:"static/svg/map.svg", type: 'chart'},
                {value:"pie_more",name:"环形图",icon:"static/svg/ring-diagram.svg", type: 'chart'},
                {value:"bar_pile",name:"柱状堆叠",icon:"static/svg/column-stacking.svg", type: 'chart'},
                {value:"bar_type_pile",name:"条形堆叠",icon:"static/svg/strip-stack.svg", type: 'chart'},
                // {value:"bar_pile_percent",name:"柱百分比",icon:"static/svg/column-stacking-percentage.svg"},
                // {value:"bar_type_pile_percent",name:"条百分比",icon:"static/svg/strip-stack-percentage.svg"},
                // {value:"tree",name:"树状图"}
            ],
            fontList: [
                {value: 'SimSun', label: '宋体'},
                {value: 'SimHei',label: '黑体'},
                {value: 'Microsoft Yahei',label: '微软雅黑'},
                {value: 'Microsoft JhengHei',label: '微软正黑体'},
                {value: 'KaiTi',label: '楷体'},
                {value: 'LiSu',label: '隶书'},
                {value: 'Times New Roman',label: 'Times New Roman'},
                {value: 'Verdana',label: 'Verdana'},
                {value: 'Arial',label: 'Arial'},
                {value: 'Times',label: 'Times'}
            ],
            fontSizeArr: ['12', '14', '16', '18', '20', '24', '28', '32', '36', '40', '44', '48', '52', '56', '60'],
            graphTitle:{
                sysn:true
            },
            titleLeft:10,
            graphSelected:'',
            basic: {
              color: '#3AC327',
              way: '求和',
              fontSize: '32',
              titlePosition: 'top',
              titleColor: '#3AC327',
              titleSize: '24',
              titleText: ''
            },
            // 图表背景控制
            backdrop: {
              control: 0,
              color: 1,
              img: 2,
              // 颜色选择器
              colorPicker: ''
            },
            // 上传文件
            file: null,
            // 上传文件后的图片访问路径
            imgUrl: '',
            echartImgURL: {},
            noTitle: ['text', 'img', 'table'],
            noLegend: ['text', 'img', 'card', 'table'],
            noXaxis: ['text', 'img', 'card', 'table', 'funnel', 'pie', 'pie_more'],
            noYaxis: ['text', 'img', 'card', 'table', 'funnel', 'pie', 'pie_more'],
            noSeries: ['text', 'img', 'card', 'table', 'funnel', 'pie', 'pie_more'],
        }
    },
    computed: {
      ring() {
        if (this.graphOptions.series && this.graphOptions.series.length > 0 && this.graphOptions.series[0].radius) {
          return {
            innerRing: parseInt(this.graphOptions.series[0].radius[0]),
            outerRing: parseInt(this.graphOptions.series[0].radius[1])
          }
        } else {
          // 默认值
          return {
            innerRing: 50,
            outerRing: 70
          }
        }
      }
    },
    watch:{
        basic:{
            handler(newValue, oldValue) {
                this.$emit("changeOptions",{key:'others',value: Object.assign({}, this.basic)})
    　　　　},
    　　　　deep: true
        },
        graphType:{
            handler(val,oldValue) {
                this.sysnOptionByTypeAndCloum({value:this.graphType,oldValue:oldValue});
    　　　　},
    　　　　deep: true
        },
        graphChartList:{
            handler(newValue, oldValue) {
                this.watchGraphChartList();
    　　　　},
    　　　　deep: true
        },
        // 图片组件的数据 监听
        echartImgURL: {
          handler(newValue, oldValue) {
            this.$emit("changeOptions",{key:'others',value: this.echartImgURL})
          },
          deep: true
        },
        graphOptions: {
          handler(val) {
            if (val.backgroundColor && typeof val.backgroundColor === 'string') {
              this.backdrop.colorPicker = val.backgroundColor
              this.backdrop.control = 1
            } else if (val.backgroundColorURL && typeof val.backgroundColorURL === 'string') {
              this.imgUrl = val.backgroundColorURL
              this.backdrop.control = 2
            }
          },
          deep: true
        }
    },
    methods:{
      changeRing () {
        this.$set(this.graphOptions.series[0],'radius',[this.ring.innerRing + '%',this.ring.outerRing + '%'])
      },
      changeChartOptions(key, value) {
      	this.$set(this.chartOptions, key, value)
      },
      changeGraphOptions(key, value) {
        this.$emit("changeOptions",{key: key,value: value})
      },
      changeSeries(series) {
        this.$emit("changeOptions",{key:'series',value:series})
      },
      // text 数据设置
      changeText(value) {
        this.$emit("changeOptions",{key:'others',value:value})
      },
        init(){
            // console.log('right',this.graphOptions)
            this.initEditInfoSet();
            // this.sysnOptionByTypeAndCloum({value:this.graphType});
            this.watchGraphChartList();
            var url =window.location.href;
            if(url.indexOf("#")!=-1){
                 url =url.substring(0,url.lastIndexOf("#"));
                if(url.indexOf("html")!=-1){
                    url = url.substring(0,url.lastIndexOf("/"))+'/';
                }
            }

            this.url=url;
        },
        watchGraphChartList(){
            var result = util.util.cloneObj(this.graphAllList);
            for(var i =0;i<result.length;i++){
                result[i].active=false;
                if (['text', 'img'].indexOf(result[i].value) !== -1) {
                  result[i].active = true
                  continue
                }
                for(var j=0;j<this.graphChartList.length;j++){
                    if(result[i].value==this.graphChartList[j]){
                        result[i].active=true;
                    }
                }
            }
            this.graphAllList =result;
        },
        //编辑 属性数据回显
        initEditInfoSet(){
            //元件基本属性回显
            util.util.extendObj(this.chartOptions,this.initdata);
            if (this.graphOptions.dataset && Array.isArray(this.graphOptions.dataset) && this.graphOptions.dataset[0].dimensions && this.graphOptions.dataset[0].dimensions.length === 2) {
              this.basic.titleText = this.graphOptions.dataset[0].dimensions[1]
            }

        },
        //返回元件基本信息
        //操作的options 已经通过事件，返回到了父组件对象
        getGraphInfo(){
            return {
                graphName:this.chartOptions.graphName,
                graphTag:this.chartOptions.graphTag,
                access:this.chartOptions.access,
                remark:this.chartOptions.remark,
                graphId:this.chartOptions.graphId
            }
        },
        formatTooltip(val) {
            return '左偏移'+val+'%';
        },
        //切换图表类型  判断当前维度和数值是否支持选择的图表类型
        choiseChartType(item){
            console.log('切换图表类型: ' + item.value)
            if(item.active!=null && item.active){
                var  next =true;
                if(item.value=='map' ){
                    next=chartUtil.judgeMapData(this.graphOptions.dataset);
                    if(!next)
                    this.$Message.error('地图类型维度必须是行政级别市(例如长沙、北京、上海)');
                }
                if (item.value === 'card') {
                  if (this.numbers && this.numbers.length === 1) {
                    this.basic.titleText = this.numbers[0].kpiName
                  }
                  this.$emit("changeOptions",{key:'others',value: this.basic})
                }else if(item.value === 'text'){
                  this.$emit("changeOptions",{key:'others',value: ''})
                }else if(item.value === 'img'){
                  this.$emit("changeOptions",{key:'others',value: this.echartImgURL})
                } else if (item.value === 'table') {
                  let tableAttr = []
                  for (let i = 0; i < this.groups.length; i++) {
                    const gp = this.groups[i];
                    tableAttr.push({
                      name: gp.dimeName,
                      color: '#333',
                    })
                  }
                  for (let i = 0; i < this.numbers.length; i++) {
                    const nm = this.numbers[i];
                    tableAttr.push({
                      name: nm.kpiName,
                      color: '#333',
                    })
                  }
                  this.$emit("changeOptions",{key:'others',value: {tableAttr: tableAttr, align: 'left', border: true, borderColor: '#e8eaec', animate: false}})
                }
                if(next){
                    this.$emit("changeType",item.value);
                    this.chartOptions.graphType =item.value;
                }
            }
        },
        optionsInit:function(groupNum,clomnNum){
            this.groupNum =groupNum ;
            this.clomnNum =clomnNum;
        },
        //判断和同步  当前选择的维度 数值还有类型  来生成对应的图表options
        sysnOptionByTypeAndCloum(item){
          console.log('changeType:' + item.value)
          if(!item.value){
              return ;
          }
          if (item.value === 'bar') {
            // 切换图形为条形图，初始化数据
            let series = []
            for (let i = 0; i < this.graphOptions.series.length; i++) {
              series.push({
                type: 'bar',
                barWidth: ''
              })
            }
            this.changeSeries(series)
            return
          } else if (item.value === 'funnel' || item.value === 'pie' || item.value === 'pie_more') {
            // 漏斗图初始化数据
            let series = []
            for (let i = 0; i < this.graphOptions.series.length; i++) {
              if (item.value === 'funnel') {
                series.push({
                  type: 'funnel',
                  label: {
                    show: true,
                    position: 'inside'
                  },
                  labelLine: {
                    show: false
                  }
                })
              } else if (item.value === 'pie') {
                series.push({
                  type: 'pie',
                  label: {
                    show: true,
                    position: ''
                  },
                  labelLine: {
                    show: true
                  }
                })
              } else if (item.value === 'pie_more') {
                series.push({
                  type: 'pie',
                  label: {
                    show: true,
                    position: ''
                  },
                  labelLine: {
                    show: true
                  },
                  radius: ['50%', '70%']
                })
              }
            }
            let color = []
            if (this.graphOptions.dataset) {
              let source = this.graphOptions.dataset[0].source
              if (source && source.length > 0) {
                for (let i = 0; i < source.length; i++) {
                  color.push('#90c4d2')
                }
              }
            }
            let graphOptionsCopy = Object.assign({color: color}, this.graphOptions)
            graphOptionsCopy.series = series
            delete graphOptionsCopy.xAxis
            delete graphOptionsCopy.yAxis
            this.$emit('changeOptions', graphOptionsCopy)
            return
          }
          for (let i = 0; i < this.graphAllList.length; i++) {
            const graphItem = this.graphAllList[i];
            if (graphItem.value === item.value && graphItem.type === 'chart') {
              new chartOptions(this,{
                  type:item.value,
                  groupnum:this.groups.length ,
                  clomnnum:this.numbers.length,
                  groups: this.groups,
                  numbers: this.numbers,
                  extendState:false
              }).initChartOptions();
              break
            }
          }
        },
        //同步  地图处理
        //在处理内容之前  ，一些具体的显示问题，还会处理一次
        //1处理map类型切换的时候  不需要展示 x  y轴  以及缩略效果，切换成其他的类型 ，需要展示
        // 背景图片文件上传 不提交
        handleBeforeUpload(file){
          // this.$set(this,'file',file)
          this.upload(file)
          return false
        },
        upload(file){
          let _this = this
          var formData = new FormData()
          let url = fileUploadURL + '/file/upload'
          getData.post('fileUploadImg', { file: file, url: url } , { dataType: 'formData' }).then(res => {
            if (res.status === 200 && res.data.code === '000') {
              _this.imgUrl = fileAccessURL + '/' + res.data.data.group + '/' + res.data.data.path
              _this.backdropSelect()
            }else{
              _this.$Message.error('文件上传失败')
            }
          })
        },
        // 背景选择
        backdropSelect() {
          // 1： 选择颜色  ； 2： 选择图片 ;  null： 不选择 默认透明
          if(this.backdrop.control === 1){
            this.$set(this.graphOptions,'graphic',[])
            let value = this.backdrop.colorPicker
            this.$set(this.graphOptions,'backgroundColorURL','')
            this.$set(this.graphOptions,'backgroundColor',value)
          }else if(this.backdrop.control === 2){
            this.$set(this.graphOptions,'backgroundColor', '')
            this.$set(this.graphOptions,'backgroundColorURL', this.imgUrl || '')
          }
        },
        innerRingSlider(value){
          let innerRingVal = value + '%'
          return innerRingVal
        },
        outerRingSlider(value){
          let outerRingVal = value + '%'
          return outerRingVal
        },
        // 展开 文本编辑器 模态框
        showEditBox(){
          this.$refs.textEditBox.show()
        }
    },
    mounted(){
        this.init()
    }
}
</script>
<style lang="less">
    .backdrop-color-picker /deep/ {
      //重写 iview组件 样式
      .ivu-input-wrapper{
        width: 193px;
        .ivu-color-picker-color{
          width: 100%;
        }
      }
      // 重写 element组件 样式
      .el-color-picker--small .el-color-picker__trigger{
        width: 193px;
      }
    }
// 重写 element组件中 按钮 样式
    .el-color-dropdown__btns{
      .el-color-dropdown__link-btn{
        line-height: 1px;
        border: 0;
        background: #fff;
      }
    }
</style>

<style lang="less" scoped>
    .box-class{
        width:100px;
    }
    .right-row /deep/ .ivu-color-picker-confirm input {
      width: 120px;
    }


</style>
